#define _CRT_SECURE_NO_WARNINGS 1
#include "DList.h"

static DListNode* DListNodeBuy(DLDatatype x)
{
	DListNode* head = (DListNode*)malloc(sizeof(DListNode));
	if (head == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	head->data = x;
	head->next = head;
	head->prev = head;
	return head;
}

void DLinit(DListNode** pphead)
{
	*pphead = DListNodeBuy(-1);
}

void DLPrint(DListNode* phead)
{
	assert(phead);
	DListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

void DLPushBack(DListNode* phead, DLDatatype x)
{
	assert(phead);	//保证指针不为空
	DListNode* newcode = DListNodeBuy(x);
	//phead phead->prev newcode
	newcode->prev = phead->prev;
	newcode->next = phead;
	//注意顺序
	phead->prev->next = newcode;
	phead->prev = newcode;
}

void DLPushFront(DListNode* phead, DLDatatype x)
{
	assert(phead);	//保证指针不为空
	DListNode* newcode = DListNodeBuy(x);
	//phead newcode phead->next
	newcode->prev = phead;
	newcode->next = phead->next;
	//注意顺序
	phead->next->prev = newcode;
	phead->next = newcode;
}

void DLPopBack(DListNode* phead)
{
	assert(phead && phead->next != phead);	//phead肯定不能为空，同时要有节点可以删除
	DListNode* del = phead->prev;
	//phead del->prev del 
	//顺序可变
	phead->prev = del->prev;
	del->prev->next = phead;
	//释放删除的节点
	free(del);
	del = NULL;
}

void DLPopFront(DListNode* phead)
{
	assert(phead && phead->next != phead);	//phead肯定不能为空，同时要有节点可以删除
	DListNode* del = phead->next;
	//phead del del-next
	//顺序可变
	phead->next = del->next;
	del->next->prev = phead;
	//释放删除的节点
	free(del);
	del = NULL;
}

void DLInsert(DListNode* pos, DLDatatype x)
{
	assert(pos);
	DListNode* newcode = DListNodeBuy(x);
	//pos newcode pos->next
	newcode->prev = pos;
	newcode->next = pos->next;
	//注意顺序
	pos->next->prev = newcode;
	pos->next = newcode;
}

DListNode* DLFind(DListNode* phead, DLDatatype x)
{
	assert(phead);
	DListNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void DLPop(DListNode* pos)
{
	assert(pos);
	//pos->prev pos pos->next
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	//释放删除的节点
	free(pos);
	pos = NULL;
}

void DLDestroy(DListNode* phead)
{
	assert(phead);
	DListNode* pcur = phead->next;
	while (pcur != phead)
	{
		DListNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}
	free(phead);
	phead = NULL;
}